package mark.tom.hawk;

import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;

import mark.tom.hawk.template.Storage;

import static mark.tom.hawk.C.DEFAULT_SP_TAG;

final class SharedPreferencesStorage implements Storage {

    public final static String STORAGE_SP_TAG = "SharedPreferences";
    private final SharedPreferences preferences;

    SharedPreferencesStorage(@NonNull Context context, @NonNull String name) {
        Util.checkNull("Context is Null", context);
        Util.checkNullOrEmpty("Name is Null", name);
        preferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    @Override
    public String tag() {
        return STORAGE_SP_TAG;
    }

    @Override
    public <T> boolean put(String key, T value) {
        Util.checkNullOrEmpty("Key is Null", key);
        return getEditor().putString(key, String.valueOf(value)).commit();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T get(String key) {
        return (T) preferences.getString(key, null);
    }

    @Override
    public boolean contains(String key) {
        return preferences.contains(key);
    }

    @Override
    public boolean delete(String key) {
        return getEditor().remove(key).commit();
    }

    @Override
    public boolean deleteAll() {
        return getEditor().clear().commit();
    }

    @Override
    public long count() {
        return preferences.getAll().size();
    }

    private SharedPreferences.Editor getEditor() {
        return preferences.edit();
    }

}
